<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>点击地图，绘制多边形</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
	<div id="map"></div>


	<div>
		<input type="text" id="delivery_range_polygon" value="" />
	</div>

    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCqsn1M2pSssz9OrldUVHP4ELTDToelVYw" defer></script>
	<script>
		let uluru;
		let zoom = 16; // 数字越大，高度越低
		let map;
		let arr = [];
		let num = 1;
		let position = [];
		let markers = {};
		let markersArray = {};
		let editCustom;
		var str = '';
		var polygonPath = {};

		// 根据网络定位
		var geolocation = 'https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCqsn1M2pSssz9OrldUVHP4ELTDToelVYw';
		(function() {
		    xhr = new XMLHttpRequest();
		    xhr.open('POST', geolocation);
		    xhr.onload = function () {
		        var response = JSON.parse(this.responseText);
		        uluru = response.location; // 获取经纬度
		        initMap(uluru); // 调用地图
		    }
		    xhr.send();
		})();

		// 地图
		function initMap(uluru) {
			map = new google.maps.Map(document.getElementById("map"), {
				center: uluru,
				zoom: zoom 
			});

			// 点击获取对应google地图上的坐标
            google.maps.event.addListener(map, 'click', function (event) {
                // 声明对象
                let obj = {};
                let latStr = parseFloat(event.latLng.lat());
                let lngStr = parseFloat(event.latLng.lng());

                // 把坐标存入对象
                obj.lat = latStr;
                obj.lng = lngStr;

                // 字符串叠加
                str += lngStr+','+latStr+'|';

                // 渲染隐藏域
                document.getElementById('delivery_range_polygon').value = str;
                
                // 存入多边形数组中
                position.push(obj);
                // 调用多边形
                polygonMarker(position);
            });
		};

		// 多边形
        function polygonMarker(position) {
            // console.log(position.);
            // 超过3个点就能成为地图，清理当前画的多边形
            if (position.length >= 3) {
                polygonPath.setMap(null);
            }

            // 创建多边形
            polygonPath = new google.maps.Polygon({
                paths: position,
                strokeColor: '#0c0',
                strokeOpacity: .5,
                strokeWeight: 2,
                strokePosition: google.maps.StrokePosition.CENTER,
                fillColor: '#f00',
                fillOpacity: 0.35,
                map:map
            });
        }
		
		window.onload = function(){
    		initMap();
		}
	</script>
</body>
</html>